package com.fantabest.common.server;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.read.biff.BiffException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.fantabest.importers.GazzettaImporter;

public class ImportServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(ImportServlet.class);	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int numberOfRecordLoaded = 0;
		try {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(3000000);
			
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(2000000);

			// Parse the request

			List<FileItem> items = upload.parseRequest(request);
			Long seasonId = null;
			// Process the uploaded items
			Iterator<FileItem> iter = items.iterator();
			FileItem playersFile = null;
			while (iter.hasNext()) {
				FileItem item = iter.next();

				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString();
					if(name.equals("seasonId"))	
						seasonId = Long.parseLong(value);
				} else {
				    String fieldName = item.getFieldName();
				    if(fieldName.equals("playersFile"))	{
				    	playersFile = item;
				    }
				}
			}
			if(playersFile!=null && seasonId!=null)
				numberOfRecordLoaded = importPlayers(playersFile,seasonId);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}	finally	{
			response.getWriter().write(numberOfRecordLoaded);
		}
	}
	
	private int importPlayers(FileItem item, Long seasonId) throws FileUploadException, IOException	{
    	int result = 0;
		try {
    		result = GazzettaImporter.getInstace().importPlayers(item.getInputStream(), 6,seasonId);
		} catch (BiffException e) {
			e.printStackTrace();
			throw new FileUploadException(e.getMessage(),e);
		}
		return result;
	}
}
